<template>
  <div>
    <cus-modal ref="modal" title="编辑" @on-visible-change="onVisibleChange" @onOk="onOk">
      <Form ref="formValidate" :model="form" :rules="ruleValidate" :label-width="100">
        <FormItem label="用户名称" prop="name" :rules="{required: true, message: '用户名称不能为空', trigger: 'blur'}">
          <Input v-model="form.name" clearable style="width: 200px" placeholder="请输入用户名称"></Input>
        </FormItem>
        <FormItem v-if="!form.id" label="登录账号" prop="loginName"
                  :rules="{required: true, message: '登录账号不能为空', trigger: 'blur'}">
          <Input v-model="form.loginName" clearable style="width: 200px" placeholder="请输入用户名称"></Input>
        </FormItem>
        <!--
        <FormItem label="登录密码" prop="password" :rules="{required: true, message: '登录密码不能为空', trigger: 'blur'}">
          <Input v-model="form.password" type="password" clearable style="width: 200px" placeholder="请输入登录密码"></Input>
        </FormItem>-->
        <FormItem label="用户角色" prop="roleList"
                  :rules="{required: true, type: 'array', message: '角色不能为空', trigger: 'change'}">
          <Select class="multiple-select" clearable v-model="form.roleList" multiple style="width:200px" size="large">
            <Option v-for="(item,ind) in roleList" :value="item.id" :key="item.id">{{ item.name }}
            </Option>
          </Select>
        </FormItem>
        <FormItem label="描述" prop="descr">
          <Input v-model="form.descr" type="textarea" :autosize="{minRows: 5,maxRows: 10}" style="width: 520px"
                 placeholder="请输入描述"/>
        </FormItem>
        <FormItem>
          <div class="flex">
            <Icon type="ios-alert" size="20" style="margin-right: 5px;" color="orange"/>
            新增用户默认密码为：12345
          </div>
        </FormItem>
      </Form>
      <Spin size="large" fix v-if="loading"></Spin>
    </cus-modal>
  </div>
</template>

<script>
  import {getUserInfo, addUser, modifyUser, getRoleList, userRelevanceRole} from '@/api/business/system'

  const form = {
    id: '',
    name: '',
    loginName: '',
    password: '',
    descr: '',
    roleList: []
  }

  export default {
    name: "userModal",
    data() {
      return {
        loading: false,
        form: form,
        roleList: [],
        ruleValidate: {}
      }
    },
    mounted() {
      this.form = this.$cu.deepClone(form);
    },
    methods: {
      onVisibleChange(v) {
        this.$refs['formValidate'].resetFields();
        if (!v) this.form = this.$cu.deepClone(form);
      },
      show() {
        this.loading = false;
        this.$refs['modal'].show = true;
        let task = [this.getRoleListApi()];
        if (this.form.id) {
          this.loading = true;
          task.push(this.getUserInfoApi())
        }
        Promise.all(task).then(() => {
          this.loading = false
        });
      },
      onOk() {
        this.$refs['formValidate'].validate(valid => {
          if (valid) {
            this.loading = true;
            if (this.form.id) {
              this.modifyUserApi();
            } else this.addUserApi();
          }
        })
      },
      // 获取用户详情
      getUserInfoApi() {
        return new Promise(resolve => {
          getUserInfo({id: this.form.id}).then(res => {
            if (res.code === 1) {
              res.data.resourceIdList = [];
              res.data.base.roleList = res.data.list;
              this.form = res.data.base;
              resolve();
            }
          })
        })
      },
      // 获取角色列表(下拉框)
      getRoleListApi() {
        return new Promise(resolve => {
          getRoleList({
            currentPage: 1,
            pageSize: 1000,
          }).then(res => {
            if (res.code === 1) {
              this.roleList = res.data.list;
              resolve();
            }
          })
        })
      },
      // 添加用户接口
      addUserApi() {
        return new Promise(resolve => {
          addUser({
            loginName: this.form.loginName,
            password: '12345',
            name: this.form.name,
            unitCode: this.$store.state.vuex_user.base.unitCode,
            descr: this.form.descr,
          }).then(res => {
            if (res.code === 1) {
              this.form.id = res.data;
              this.userRelevanceRoleApi().then(() => {
                this.loading = false;
                this.$Message.success('添加成功');
                this.$refs['modal'].show = false;
                this.$parent.onInit();
              })
              resolve();
            } else this.loading = false
          })
        })
      },
      // 编辑用户接口
      modifyUserApi() {
        return new Promise(resolve => {
          modifyUser({
            id: this.form.id,
            loginName: this.form.loginName,
            password: this.form.password,
            name: this.form.name,
            descr: this.form.descr,
          }).then(res => {
            if (res.code === 1) {
              this.userRelevanceRoleApi().then(() => {
                this.loading = false;
                this.$Message.success('编辑成功');
                this.$refs['modal'].show = false;
                this.$parent.onInit();
              })
              resolve();
            } else this.loading = false
          })
        })
      },
      // 用户关联角色
      userRelevanceRoleApi() {
        return new Promise(resolve => {
          userRelevanceRole({userId: this.form.id, roleList: JSON.stringify(this.form.roleList)}).then(res => {
            if (res.code === 1) {
              resolve();
            } else this.loading = false;
          })
        })
      }
    }
  }
</script>

<style scoped lang="less">
  .permission {
    height: 300px;
    width: 500px;
    border: 1px solid #dcdee2;
    overflow-y: auto;
    border-radius: 2px;
    padding: 0 0 0 10px;
  }
</style>
